package com.ruoyi.collect.controller;

import com.ruoyi.collect.domain.CollectTask;
import com.ruoyi.collect.service.ICollectEngineService;
import com.ruoyi.collect.service.ICollectTaskService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 采集任务控制器
 *
 * @author ruoyi
 * @date 2025-11-07
 */
@RestController
@RequestMapping("/collect/task")
public class CollectTaskController extends BaseController {

    @Autowired
    private ICollectTaskService collectTaskService;

    @Autowired
    private ICollectEngineService collectEngineService;

    /**
     * 查询采集任务列表
     */
    @PreAuthorize("@ss.hasPermi('collect:task:list')")
    @GetMapping("/list")
    public TableDataInfo list(CollectTask collectTask) {
        startPage();
        List<CollectTask> list = collectTaskService.selectCollectTaskList(collectTask);
        return getDataTable(list);
    }

    /**
     * 导出采集任务列表
     */
    @PreAuthorize("@ss.hasPermi('collect:task:export')")
    @Log(title = "采集任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CollectTask collectTask) {
        List<CollectTask> list = collectTaskService.selectCollectTaskList(collectTask);
        ExcelUtil<CollectTask> util = new ExcelUtil<CollectTask>(CollectTask.class);
        util.exportExcel(response, list, "采集任务数据");
    }

    /**
     * 获取采集任务详细信息
     */
    @PreAuthorize("@ss.hasPermi('collect:task:query')")
    @GetMapping(value = "/{taskId}")
    public AjaxResult getInfo(@PathVariable("taskId") Long taskId) {
        return AjaxResult.success(collectTaskService.selectCollectTaskById(taskId));
    }

    /**
     * 新增采集任务
     */
    @PreAuthorize("@ss.hasPermi('collect:task:add')")
    @Log(title = "采集任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CollectTask collectTask) {
        return toAjax(collectTaskService.insertCollectTask(collectTask));
    }

    /**
     * 修改采集任务
     */
    @PreAuthorize("@ss.hasPermi('collect:task:edit')")
    @Log(title = "采集任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CollectTask collectTask) {
        return toAjax(collectTaskService.updateCollectTask(collectTask));
    }

    /**
     * 删除采集任务
     */
    @PreAuthorize("@ss.hasPermi('collect:task:remove')")
    @Log(title = "采集任务", businessType = BusinessType.DELETE)
    @DeleteMapping("/{taskIds}")
    public AjaxResult remove(@PathVariable Long[] taskIds) {
        return toAjax(collectTaskService.deleteCollectTaskByIds(taskIds));
    }

    /**
     * 执行采集任务
     */
    @PreAuthorize("@ss.hasPermi('collect:task:execute')")
    @PostMapping("/execute/{taskId}")
    public AjaxResult executeTask(@PathVariable Long taskId) {
        collectEngineService.executeTaskAsync(taskId);
        return AjaxResult.success("任务已启动");
    }

    /**
     *
     * 停止采集任务
     */
    @PreAuthorize("@ss.hasPermi('collect:task:stop')")
    @PostMapping("/stop/{taskId}")
    public AjaxResult stopTask(@PathVariable Long taskId) {
        boolean result = collectEngineService.stopTask(taskId);
        return result ? AjaxResult.success("任务已停止")
                      : AjaxResult.error("停止任务失败");
    }

    /**
     * 暂停采集任务
     */
    @PreAuthorize("@ss.hasPermi('collect:task:pause')")
    @PostMapping("/pause/{taskId}")
    public AjaxResult pauseTask(@PathVariable Long taskId) {
        boolean result = collectEngineService.pauseTask(taskId);
        return result ? AjaxResult.success("任务已暂停")
                      : AjaxResult.error("暂停任务失败");
    }

    /**
     * 恢复采集任务
     */
    @PreAuthorize("@ss.hasPermi('collect:task:resume')")
    @PostMapping("/resume/{taskId}")
    public AjaxResult resumeTask(@PathVariable Long taskId) {
        boolean result = collectEngineService.resumeTask(taskId);
        return result ? AjaxResult.success("任务已恢复")
                      : AjaxResult.error("恢复任务失败");
    }

    /**
     * 获取任务状态
     */
    @GetMapping("/status/{taskId}")
    public AjaxResult getTaskStatus(@PathVariable Long taskId) {
        String status = collectEngineService.getTaskStatus(taskId);
        return AjaxResult.success(status);
    }

    /**
     * 采集站点所有数据
     */
    @PreAuthorize("@ss.hasPermi('collect:task:collect')")
    @PostMapping("/all/{siteId}")
    public AjaxResult collectAll(@PathVariable Long siteId) {
        CollectTask task = collectEngineService.collectAll(siteId);
        if (task != null) {
            Map<String, Object> data = new HashMap<>();
            data.put("taskId", task.getTaskId());
            data.put("taskName", task.getTaskName());
            return AjaxResult.success("采集已启动", data);
        }
        return AjaxResult.error("启动采集失败");
    }

    /**
     * 采集站点最新数据
     */
    @PreAuthorize("@ss.hasPermi('collect:task:collect')")
    @PostMapping("/recent/{siteId}/{hours}")
    public AjaxResult collectRecent(@PathVariable Long siteId, @PathVariable Integer hours) {
        CollectTask task = collectEngineService.collectRecent(siteId, hours);
        if (task != null) {
            Map<String, Object> data = new HashMap<>();
            data.put("taskId", task.getTaskId());
            data.put("taskName", task.getTaskName());
            return AjaxResult.success("采集已启动", data);
        }
        return AjaxResult.error("启动采集失败");
    }

    /**
     * 按类型采集
     */
    @PreAuthorize("@ss.hasPermi('collect:task:collect')")
    @PostMapping("/type/{siteId}/{typeId}")
    public AjaxResult collectByType(@PathVariable Long siteId, @PathVariable String typeId) {
        CollectTask task = collectEngineService.collectByType(siteId, typeId);
        if (task != null) {
            Map<String, Object> data = new HashMap<>();
            data.put("taskId", task.getTaskId());
            data.put("taskName", task.getTaskName());
            return AjaxResult.success("采集已启动", data);
        }
        return AjaxResult.error("启动采集失败");
    }

    /**
     * 按ID采集
     */
    @PreAuthorize("@ss.hasPermi('collect:task:collect')")
    @PostMapping("/ids/{siteId}")
    public AjaxResult collectByIds(@PathVariable Long siteId, @RequestBody Map<String, String> params) {
        String ids = params.get("ids");
        if (ids == null || ids.trim().isEmpty()) {
            return AjaxResult.error("ID列表不能为空");
        }
        CollectTask task = collectEngineService.collectByIds(siteId, ids);
        if (task != null) {
            Map<String, Object> data = new HashMap<>();
            data.put("taskId", task.getTaskId());
            data.put("taskName", task.getTaskName());
            return AjaxResult.success("采集已启动", data);
        }
        return AjaxResult.error("启动采集失败");
    }

    /**
     * Test collection
     */
    @PreAuthorize("@ss.hasPermi('collect:task:test')")
    @GetMapping("/test/{siteId}")
    public AjaxResult testCollection(@PathVariable Long siteId,
                                     @RequestParam(defaultValue = "5") Integer limit) {
        String result = collectEngineService.testCollection(siteId, limit);
        return AjaxResult.success(result);
    }
}